package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"goproject/commonType"
	"goproject/requestProxy"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

// GetrpxyData 函数处理请求
func GetrpxyData(c *gin.Context) {
	// 打印当前工作目录
	wd, err := os.Getwd()
	if err != nil {
		log.Fatalf("无法获取当前工作目录: %v", err)
	}
	fmt.Printf("当前工作目录: %s\n", wd)

	// 打开 JSON 文件
	filePath := filepath.Join(wd, "/controller/traceData.json")
	file, err := os.Open(filePath)
	if err != nil {
		log.Fatalf("无法打开文件: %v", err)
	}
	defer file.Close()

	// 读取文件内容
	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Fatalf("无法读取文件: %v", err)
	}

	// 解析 JSON 数据
	var traceItem commonType.TraceItem
	if err := json.Unmarshal(data, &traceItem); err != nil {
		log.Fatalf("无法解析 JSON 数据: %v", err)
	}
	podInfolist, _ := GetPodNamesFromJaeger(traceItem)
	// 从请求体中获取 podInfolist
	//if err := c.ShouldBindJSON(&podInfolist); err != nil {
	//	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	//	return
	//}
	// 调用 requestProxy.GetRequestData 获取请求数据
	requestData, _ := requestProxy.GetRequestData(context.Background(), podInfolist, "sock-shop")

	// 返回 JSON 响应
	c.JSON(http.StatusOK, requestData)
}

// GetPodNamesFromJaeger 函数处理 Jaeger 的追踪数据
func GetPodNamesFromJaeger(traceItem commonType.TraceItem) ([]commonType.PodInfo, error) {
	podInfoMap := make(map[string]*commonType.PodInfo)
	spans := traceItem.Spans

	// 过滤出有效的 span（请求的发起者）
	for _, span := range spans {
		var isOutbound bool
		for _, tag := range span.Tags {
			if tag.Key == "upstream_cluster.name" && strings.Contains(tag.Value, "outbound") {
				isOutbound = true
				break
			}
		}
		if !isOutbound {
			continue
		}

		// 查找对应 podName
		targetSpan := commonType.Span{}
		for _, innerspan := range spans {
			for _, ref := range innerspan.References {
				if ref.RefType == "CHILD_OF" && ref.SpanID == span.SpanID {
					targetSpan = innerspan
					break
				}
			}
		}
		// 处理podname
		for _, tag := range targetSpan.Tags {
			if tag.Key == "node_id" {
				parts := strings.Split(tag.Value, "~")
				if len(parts) >= 3 {
					podPart := strings.Split(parts[2], ".")
					if len(podPart) >= 1 {
						podName := podPart[0]
						if podInfo, exists := podInfoMap[podName]; exists {
							podInfo.SpanList = append(podInfo.SpanList, span.SpanID)
						} else {
							podInfoMap[podName] = &commonType.PodInfo{
								PodName:  podName,
								SpanList: []string{span.SpanID},
							}
						}
					}
				}
			}
		}
	}
	podInfoList := make([]commonType.PodInfo, 0, len(podInfoMap))
	for _, podInfo := range podInfoMap {
		podInfoList = append(podInfoList, *podInfo)
	}

	return podInfoList, nil
}

func GetAllPods(c *gin.Context) {
	requestProxy.GetAllPods()
	c.JSON(http.StatusOK, nil)
}
